package com.woniu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.entity.Documents;
import com.woniu.service.DocumentsService;
import com.woniu.mapper.DocumentsMapper;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
* @author nanqiao
* @description 针对表【documents(文档表)】的数据库操作Service实现
* @createDate 2025-06-09 11:12:20
*/
@Service
public class DocumentsServiceImpl extends ServiceImpl<DocumentsMapper, Documents>
    implements DocumentsService{
    @Autowired
    private DocumentsMapper documentsMapper;
    @Autowired
    private MinioClient minioClient;

    @Override
    public Documents addDocuments(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        long size = file.getSize();
        try {
            InputStream inputStream = file.getInputStream();
            // 通过 stream 流来上传图片
            ObjectWriteResponse oss = minioClient.putObject(
                    PutObjectArgs.builder()
                            .stream(inputStream, size, -1L)
                            .object(fileName)
                            .bucket("java112")
                            .build()
            );
            // 获取文件的访问路径 share 分享的 url 地址
            String url = minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket("java112")
                            .object(fileName)
                            .build()
            );

            // 创建 UploadResult 对象
            Documents documents = new Documents();
            documents.setDocumentsName(fileName);
            documents.setDoctumentsUrl(url);

            // 保存上传结果到数据库
            saveDocuments(documents);

            return documents;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void saveDocuments(Documents documents) {
        documentsMapper.insertDocuments(documents);
    }

}




